xquery version "1.0-ml";

module namespace plib = "http://porvino.com/lib";

declare function globalNav() {
    globalNav("")
};

declare function globalNav($searchterm) {
    <div style="margin:20px;">
        <a href="/porvino/lib/newWine.xqy">Add Wine</a> | 
        <a href="/porvino/list/listWines.xqy">List All Wines</a> | 
        Search <input type="text" onchange="location.href='/porvino/search/searchWines.xqy?term='+this.value;" value="{$searchterm}"></input>
    </div>
};

declare function search-result-transform($r, $c, $o) {
    $r
};

declare function listWines($wines) {
    <table id="wineList" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
        <thead>
            <tr>
                <th>vintage</th>
                <th>winery</th>
                <th>name</th>
                <th>primary varietal</th>
                <th>available</th>
                <th>drink</th>
                <th>expire</th>
                <th>future</th>
                <th>location</th>
            </tr>
        </thead>
        <tbody>
        {
             for $wine in $wines
                let $winery := $wine/winery/text()
                let $name := $wine/name/text()
                let $vintage := $wine/vintage/text()
                let $primary-varietal := $wine/varietal/text()
                let $all-varietals := $wine/blend//blendPart/blendVarietal/text()
                let $avail := 
                    if($wine/inventory/inventoryEntry/onhand != "")
                    then fn:sum(for $i in $wine/inventory/inventoryEntry/onhand 
                        return if (($i!="") and ($i/../future != "true")) then $i/text() else 0)
                    else 0      
                let $matstart := $wine/start/text()
                let $matend := $wine/end/text()
                let $wineid := $wine/@id
                let $future :=
                    let $fut :=
                        fn:sum(for $i in $wine/inventory/inventoryEntry/future 
                            return if ($i ="true") then $i/../quantity/text() else 0)
                    return if ($fut = 0) then "" else $fut
                 let $location := $wine/inventory/inventoryEntry/location/text()
                order by $name, $vintage
            return 
            <tr onclick="window.location='/porvino/edit/editWine.xqy?id={$wineid}'"><td>{$vintage}</td><td>{$winery}</td><td>{$name}</td>
            <td title="{$all-varietals}">{$primary-varietal}</td><td>{$avail}</td><td>{$matstart}</td><td>{$matend}</td><td>{$future}</td><td>{$location}</td></tr>
        }
        </tbody>
    </table>
};